import React, { forwardRef, useState, useImperativeHandle, useRef, useEffect } from "react";
import { Form, Popover, DatePicker, Input, Radio, InputNumber, Tag, Button, Space, Modal, Divider, Icon, message, Table, Spin, Progress, Tooltip } from '@bytedance/mona-ui';
import type { ColumnProps } from '@bytedance/mona-ui/es/components/table';
import { addCouponFun, stopAddConter } from './couponFunc'
import GoodsTable from './goodsTable'
import { useAppSelector } from "~store"
import moment from 'moment';
import 'moment/locale/zh-cn';
import { checkPromotionProductList } from "@Api/productApi"

moment.locale('zh-cn');
const { RangePicker } = DatePicker;
let scoyerDatetle = '因抖店规则调整，单品优惠券同一时间段只能设置一张优惠券，有全店优惠券的情况下单品优惠券优惠力度需大于全店优惠券！'// 目前正在调整策略，尽情期待！！！
function Coupon(props, ref) {


    const [addCouponConfig, setAddCouponConfig] = useState<any>({
        displayChannel: 1,
        coupon_name: '',
        period_type: 1,
        valid_period: '',
        goodsScope: 2,
        getTime: [moment().startOf('day'), moment().add(1, 'day').startOf('day').subtract(1, 'second')],
        dataWei: [moment().startOf('day'), moment().add(1, 'day').startOf('day').subtract(1, 'second')],
        start_apply_time: moment().startOf('day').unix(),
        end_apply_time: moment().add(1, 'day').startOf('day').subtract(1, 'second').unix(),
        start_time: moment().startOf('day').unix(),
        expire_time: moment().add(1, 'day').startOf('day').subtract(1, 'second').unix(),
        couponGoodsNum: 30,
        couponAfterText: '',
        goodsScopeSelectStatus: false,
        goodsScopeSelectText: ''
    })
    let { period_type, goodsScope, start_apply_time, end_apply_time } = addCouponConfig

    useEffect(() => {
        // console.log('start_apply_time, end_apply_time', start_apply_time, end_apply_time)
        // console.log('时间修改， 需要检查是否需要请求规则')
        checkPromotionProductListFunter()
    }, [start_apply_time, end_apply_time])
    // 检查可用商品
    async function checkPromotionProductListFunter() {
        const getTimetype = {
            "validate_type": 1,
            "participate_type": 2,
            "activity_tool_type": 7,
            "activity_tool_discount_type": 1,
            "support_type": 5,
            "start_time": start_apply_time,
            "end_time": end_apply_time
        }
        const getAtserNow: any = await checkPromotionProductList(getTimetype)
        console.log('getAtserNow', getAtserNow)
        setCouponTableDataShop([])
        setCouponTableDataAll([])
        if (goodsScope == 1 && selectGoodsdRef.current) {
            selectGoodsdRef.current?.getProdectListFunAs();
            // console.log('goodsList', goodsList)
            // return
        }
        if (!getAtserNow.code) {
            if (!getAtserNow.data.activity_check_info.check_pass) {
                // console.log('conflict_activity_info', getAtserNow.data.activity_check_info.conflict_activity_info)
                setAddCouponConfig({ ...addCouponConfig, goodsScope: 1, goodsScopeSelectStatus: true, goodsScopeSelectText: getAtserNow.data.activity_check_info.reject_reason })
            } else {
                setAddCouponConfig({ ...addCouponConfig, goodsScopeSelectStatus: false, goodsScopeSelectText: '' })
            }
        }
    }
    const [addCouponList, setAddCouponList] = useState(false)

    const [couponListDataShop, setCouponListDataShop] = useState([couponListDataFater(2)])
    function couponListDataFater(params) {
        return {
            favoured_type: params === 1 ? 22 : 42,
            discountType: 1,
            discount: '',
            credit: '',
            threshold: '',
            total_amount: '',
            max_apply_times: 1,
            reseteStatus: {
                errLijStatus: '',
                errLijTitle: null,
                errmonStatus: '',
                errmonTitle: null,
                errzekouStatus: '',
                errzekouTitle: null,
                fanStatus: '',
                fanTitle: null

            }

        }

    }
    const [couponListDataAll, setCouponListDataAll] = useState([couponListDataFater(1)])

    interface ColumnPropsType {
        index: number;
        name: string;
    }
    const [couponTableDataAll, setCouponTableDataAll] = useState([])
    const [couponTableDataShop, setCouponTableDataShop] = useState([])
    const [editCouponStatus, setEditCounponStatus] = useState({
        status: false,
        index: -1
    })
    const couponTitle: ColumnProps<ColumnPropsType>[] = [
        {
            title: 'ID',
            key: '5',
            // dataIndex: 'ID',
            align: "center",
            render: (_, record, index) => {
                return ++index
            },
        },
        {
            title: '券内容',
            key: '0',
            dataIndex: 'couponName',
            align: "center",
        },
        {
            title: '力度',
            key: '1',
            dataIndex: 'meter',
            align: "center",
        },
        {
            title: '发行量',
            key: '2',
            dataIndex: 'total_amount',
            align: "center",
        },
        {
            title: '每人领',
            key: '3',
            dataIndex: 'max_apply_times',
            align: "center",
        },
        {
            title: '操作',
            key: '4',
            dataIndex: 'birth',
            align: "center",
            render: (_, record, index) => {
                return (
                    <Space>
                        <Icon
                            type="EditIcon" style={{
                                fontSize: 16,
                                color: '#2970FF',
                                cursor: 'pointer'
                            }}
                            onClick={() => {
                                console.log('编辑')
                                setEditCounponStatus({
                                    status: true,
                                    index
                                })
                                setAddCouponList(true)
                                // let setTabData = goodsScope === 1 ? couponTableDataShop : couponTableDataAll
                                // let setTabFun = goodsScope === 1 ? setCouponTableDataShop : setCouponTableDataAll
                                // setTabData.splice(index, 1)
                                // setTabFun([...setTabData])
                            }}
                        ></Icon>
                        <Icon
                            type="DeleteIcon" style={{
                                fontSize: 16,
                                color: 'red',
                                cursor: 'pointer'
                            }}
                            onClick={() => {
                                let setTabData = goodsScope === 1 ? couponTableDataShop : couponTableDataAll
                                let setTabFun = goodsScope === 1 ? setCouponTableDataShop : setCouponTableDataAll
                                setTabData.splice(index, 1)
                                setTabFun([...setTabData])
                            }}
                        ></Icon>
                    </Space>

                );
            },
        }]
    useImperativeHandle(ref, () => ({
        someMethod,
    }));

    const stipInfo = {
        resetData: null,
        addUnser: 0,
        allInstallNum: 0,
        stip: 0,
        stopKet: false,
        success: 0,
        fail: 0
    }
    const [addstipdata, setaddstipdata] = useState(stipInfo)
    const [isAllEndStatus, setIsAllEndStatus] = useState(false)
    const [isUserStopStatus, setisUserStopStatus] = useState(false)
    type ChildMethods = {
        // 子组件暴露给父组件的方法
        getSelectGoods: () => void;
        getProdectListFunAs: () => void;
    };
    const selectGoodsdRef = useRef<ChildMethods>(null);
    const isBuyStatus = useAppSelector(
        (state) => state.jinritemaiProduct.isBuyStatus
    )
    const someMethod = async () => {
        if (isBuyStatus.status) {
            Modal.confirm({
                title: isBuyStatus.title,
                content: isBuyStatus.content,
                icon: null,
                okText: isBuyStatus.okText,
                cancelText: " 取消",
                onOk: () => {
                    open(isBuyStatus.url)
                    return
                }
            })
            return
        }
        const upDataInfo = addCouponConfig.goodsScope == 1 ? couponTableDataShop : couponTableDataAll
        // console.log(' addCouponConfig.goodsScope6666666 ', addCouponConfig.goodsScope)
        // console.log('upDataInfo选择结果', upDataInfo)
        if (!upDataInfo || !upDataInfo.length) {
            message.warning(`请先创建${addCouponConfig.goodsScope == 1 ? '指定商品' : '全店商品'}优惠券`)
            return
        }
        Modal.warning({
            title: '提示',
            content: scoyerDatetle,
            // showCancel: false,
            okText: '继续设置',
            onOk: (close) => {
                let goodsList: any = []
                if (selectGoodsdRef.current) {
                    goodsList = selectGoodsdRef.current?.getSelectGoods();
                    // console.log('goodsList', goodsList)
                    // return
                }
                // 子组件的方法实现
                // const { goodsScope } = addCouponConfig

                addCouponFun({
                    upDataInfo,
                    addCouponConfig,
                    selectGoodsKeys: goodsList // 到子组件获取
                }, (data) => {
                    // console.log('进度', data)
                    if (data.stopKet) {
                        setStopKetStrt(false)
                        setisUserStopStatus(true)
                        window.onbeforeunload = null
                        return
                    }
                    window.onbeforeunload = function (event) {
                        return "您正在创建优惠券，是否确认离开" // 新版本浏览器不起作用
                    }
                    setShowAddSetStatus(true)
                    // console.log('data...', data)
                    setaddstipdata({ ...data })
                }).then(() => {
                    setIsAllEndStatus(true)
                    message.success('创建完成')
                    window.onbeforeunload = null
                })
                return close()
                // console.log('addData', addData)

            }

        })


    };
    const [showAddSetStatus, setShowAddSetStatus] = useState(false)
    const [stopKetStrt, setStopKetStrt] = useState(false)
    function backOpenter() {
        setShowAddSetStatus(false)
        setisUserStopStatus(false)
        setIsAllEndStatus(false)
        setaddstipdata(stipInfo)
        setStopKetStrt(false)
        selectGoodsdRef.current?.getProdectListFunAs();
        checkPromotionProductListFunter()
        // setCouponTableDataShop([])
        // setCouponTableDataAll([])
        // props && props.setcurrent && props.setcurrent('')
    }
    const [showAddCouponStuats, setShowAddCouponStuats] = useState((_ => {
        const dlyfundata = localStorage.getItem('dlyfundataAddun')
        const infoDate = {
            addconpon: true
        }
        setTimeout(_ => {
            localStorage.setItem('dlyfundataAddun', JSON.stringify(infoDate))
        }, 200)
        try {
            const getJson = JSON.parse(dlyfundata)
            if (getJson.addconpon) return false
        } catch (error) {
            return true
        }
        return true
    })())
    const [focusState, setFocusState] = useState<'start' | 'end' | null>('start');
    function disabledDate(current) {
        // console.log('addCouponConfig.getTime', addCouponConfig.getTime)
        // console.log('focusState', addCouponConfig.getTime?.[0])
        if (focusState === 'start') {
            return (current && (current < moment().subtract(1, 'days') || current > moment().add(1, 'years')));
        }
        if (focusState === 'end') {
            return (current && (current < moment(addCouponConfig.getTime?.[0]).subtract(1, 'days') || current > moment(addCouponConfig.getTime?.[0]).add(1, 'years')));
        }
    }
    const [focusStateUse, setFocusStateUse] = useState<'start' | 'end' | null>('start');

    function disabledDateUse(current) {
        // console.log('addCouponConfig.getTime', addCouponConfig.getTime)
        // console.log('focusState', addCouponConfig.getTime?.[0])
        if (focusStateUse === 'start') {
            if (!addCouponConfig.getTime?.[1]) {
                return (current && (current < moment().subtract(1, 'days') || current > moment().add(14, 'days')));

            } else {
                return (current && (current < moment().subtract(1, 'days') || current > moment(addCouponConfig.getTime?.[1]).add(14, 'days')));
            }
        }
        if (focusStateUse === 'end') {
            return (current && (current < moment(addCouponConfig.dataWei?.[0]).subtract(1, 'days') || current > moment(addCouponConfig.dataWei?.[0]).add(180, 'days')));
        }
    }
    return (<div>
        <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 16 }}
            layout="horizontal"
            name="couponConfig"
            initialValues={addCouponConfig}
        >
            {/* <Form.Item noStyle>
                <h2 className="conet" style={{
                    color: 'red'
                }}>{scoyerDatetle}</h2>
            </Form.Item> */}
            <Form.Item
                name="getTime"
                label="领取时间"
                rules={[
                    {
                        required: true,
                        message: '领取时间必填',
                    },
                ]}
            >
                <RangePicker
                    ranges={{
                        '1天内': [moment(), moment().add(1, 'days')],
                        '今晚0点一天内': [moment().add(1, 'day').startOf('day'), moment().add(2, 'day').startOf('day').subtract(1, 'second')],
                        '3天内': [moment(), moment().add(3, 'days')],
                        '今晚0点三天内': [moment().add(1, 'day').startOf('day'), moment().add(4, 'day').startOf('day').subtract(1, 'second')],
                        '一周内': [moment(), moment().add(7, 'days')],
                        '今晚0点一周内': [moment().add(1, 'day').startOf('day'), moment().add(8, 'day').startOf('day').subtract(1, 'second')],
                    }}
                    // timePickerProps={{
                    //     format: 'HH:mm:ss',
                    //   }}
                    showTime
                    disabledDate={disabledDate}
                    // disabledTime={disabledRangeTime}
                    format="YYYY-MM-DD HH:mm:ss"
                    onFocus={(_, { range }) => {
                        console.log('onFocus2', range);
                        setFocusState(range);
                    }}
                    onOpenChange={open => {
                        if (!open) {
                            setFocusState('start');
                        }
                    }}
                    onCalendarChange={(e: any) => {
                        addCouponConfig.getTime = e
                        setAddCouponConfig({ ...addCouponConfig })
                    }}
                    onChange={(e) => {
                        console.log('e', e[0].unix(), e[1].unix())
                        addCouponConfig.getTime = e
                        if (e) {
                            addCouponConfig.start_apply_time = e[0].unix()
                            addCouponConfig.end_apply_time = e[1].unix()
                        } else {
                            addCouponConfig.start_apply_time = ''
                            addCouponConfig.end_apply_time = ''
                        }

                        setAddCouponConfig({ ...addCouponConfig })
                    }}></RangePicker>
            </Form.Item>
            <Form.Item
                name="period_type"
                label="使用时间"
                rules={[
                    {
                        required: true,
                        message: '使用时间必选',
                    },
                ]}
            >
                <Radio.Group onChange={(e: any) => {
                    // console.log('e', e)
                    addCouponConfig.period_type = e.target.value
                    setAddCouponConfig({ ...addCouponConfig })
                }}>
                    <Radio value={1}>限制日期范围</Radio>
                    <Radio value={2}>限制有效天数</Radio>
                </Radio.Group>
            </Form.Item>
            {period_type === 1 && <Form.Item
                name="dataWei"
                label="日期范围"
                rules={[
                    {
                        required: true,
                        message: '限制日期范围必填',
                    },
                    {
                        validator: (_, value) => {
                            if (!value) {
                                return Promise.reject();
                            }
                            if (!value[0] || !value[1]) {
                                return Promise.reject(new Error('限制日期范围必填'));
                            }
                            if (!addCouponConfig.end_apply_time) {
                                return Promise.resolve()
                            }
                            if (addCouponConfig.end_apply_time > value[1].unix()) {
                                return Promise.reject(new Error('使用结束时间不能早于领取结束时间'));
                            }
                            return Promise.resolve()
                        }
                    }
                ]}

            >
                <RangePicker
                    ranges={{
                        '1天内': [moment(), moment().add(1, 'days')],
                        '今晚0点一天内': [moment().add(1, 'day').startOf('day'), moment().add(2, 'day').startOf('day').subtract(1, 'second')],
                        '3天内': [moment(), moment().add(3, 'days')],
                        '今晚0点三天内': [moment().add(1, 'day').startOf('day'), moment().add(4, 'day').startOf('day').subtract(1, 'second')],
                        '一周内': [moment(), moment().add(7, 'days')],
                        '今晚0点一周内': [moment().add(1, 'day').startOf('day'), moment().add(8, 'day').startOf('day').subtract(1, 'second')],
                    }}
                    // timePickerProps={{
                    //     format: 'HH:mm:ss',
                    //   }}
                    showTime
                    disabledDate={disabledDateUse}
                    // disabledTime={disabledRangeTime}
                    onFocus={(_, { range }) => {
                        // console.log('onFocus2', range);
                        setFocusStateUse(range);
                    }}
                    onOpenChange={open => {
                        if (!open) {
                            setFocusStateUse('start');
                        }
                    }}
                    onCalendarChange={(e: any) => {
                        addCouponConfig.dataWei = e
                        setAddCouponConfig({ ...addCouponConfig })
                    }}
                    format="YYYY-MM-DD HH:mm:ss"
                    onChange={(e) => {
                        // console.log('e', e)
                        addCouponConfig.dataWei = e
                        if (e) {
                            addCouponConfig.start_time = e[0].unix()
                            addCouponConfig.expire_time = e[1].unix()
                        } else {
                            addCouponConfig.start_time = ''
                            addCouponConfig.expire_time = ''
                        }

                        setAddCouponConfig({ ...addCouponConfig })
                    }}></RangePicker>
            </Form.Item>}
            {period_type === 2 && <Form.Item
                name="valid_period"
                label="领取当天起"
                rules={[
                    {
                        required: true,
                        message: '限制有效天数必填',
                    },
                ]}
            >
                <InputNumber
                    placeholder="请输入数字"
                    min={1}
                    max={180}
                    unit='天内可使用'
                    onChange={(e: any) => {
                        addCouponConfig.valid_period = e
                        setAddCouponConfig({ ...addCouponConfig })
                    }}
                />
            </Form.Item>}
            <Form.Item
                // name="goodsScope"
                label="商品范围"
                rules={[
                    {
                        required: true,
                        message: '商品范围必填',
                    },
                ]}
            >
                <Radio.Group value={addCouponConfig.goodsScope} onChange={(e: any) => {
                    addCouponConfig.goodsScope = e.target.value
                    setAddCouponConfig({ ...addCouponConfig })
                }}>
                    <Tooltip title={addCouponConfig.goodsScopeSelectText}>
                        <Radio value={2} disabled={addCouponConfig.goodsScopeSelectStatus}>全店商品（店铺券）</Radio>
                    </Tooltip>
                    <Radio value={1}>指定商品（商品券）</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                name="couponList"
                label="优惠券">
                <Space direction="vertical" style={{
                    width: '100%'
                }}>
                    <Button type="primary" size="mini" onClick={() => {
                        setAddCouponList(true)
                    }}>添加优惠券</Button>
                    {(() => {
                        const tableData = goodsScope === 2 ? couponTableDataAll : couponTableDataShop
                        return <Table
                            locale={{
                                emptyText: <div>数据为空，请前往<Button type="link" onClick={() => {
                                    setAddCouponList(true)
                                }}>添加优惠券</Button></div>
                            }}
                            rowKey="index"
                            columns={couponTitle}
                            dataSource={tableData}
                            bordered
                            pagination={{ hideOnSinglePage: true }}
                        />
                    })()}

                </Space>
            </Form.Item>
            {goodsScope === 1 && (
                <>
                    <Form.Item
                        name="couponGoodsNum"
                        label="每个券活动商品数"
                        rules={[
                            {
                                required: true,
                                message: '每个券活动商品数必填',
                            },
                        ]}
                    >
                        <InputNumber
                            placeholder="请输入数字"
                            min={1}
                            max={200}
                            unit='个'
                            onChange={(e: any) => {
                                addCouponConfig.couponGoodsNum = e
                                setAddCouponConfig({ ...addCouponConfig })
                            }}
                        />
                    </Form.Item>
                </>
            )}
            <Form.Item
                name="couponAfterText"
                label="优惠券前缀">
                <Input placeholder="可添加优惠券前缀名称" onChange={(e) => {
                    addCouponConfig.couponAfterText = e.target.value.slice(0, 5)
                    setAddCouponConfig({ ...addCouponConfig })
                }} maxLength={5} style={{
                    width: 250
                }}></Input>
            </Form.Item>
            {goodsScope === 1 && <Divider />}
        </Form>
        {goodsScope === 1 && <GoodsTable ref={selectGoodsdRef} addCouponConfig={addCouponConfig} couponTableDataShop={couponTableDataShop}></GoodsTable>}
        {showAddSetStatus &&
            <div
                style={{
                    background: 'rgba(255, 255, 255)',
                    width: '100%',
                    height: '100%',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    zIndex: 100,
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center'
                }}>
                <div className="topContent" style={{
                    color: '#252931',
                    margin: 0,
                    fontSize: 16,
                    fontWeight: 500,
                    padding: '16px 24px',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '100%',
                    borderBottom: '1px solid #eeeff0'
                }}>
                    {stopKetStrt ? '正在停止' : isUserStopStatus ? '已手动停止' : isAllEndStatus ? `已完成` : '正在创建'}
                </div>
                <Space direction="vertical" align="center" size={16}>
                    {isUserStopStatus ? <Icon style={{ color: '#c21' }} svgProps={{ style: { width: 60, height: 60 } }} type="InfoIcon" /> : isAllEndStatus ?
                        <svg
                            width="120"
                            height="120"
                            viewBox="0 0 120 120"
                            fill="none"
                            xmlns="http://www.w3.org/2000/svg">
                            <g clip-path="url(#clip0_445_33713)">
                                <path
                                    fill-rule="evenodd"
                                    clip-rule="evenodd"
                                    d="M60 93C78.2254 93 93 78.2254 93 60C93 41.7746 78.2254 27 60 27C41.7746 27 27 41.7746 27 60C27 78.2254 41.7746 93 60 93ZM77.6492 53.4642C79.1589 51.49 78.7823 48.6658 76.8081 47.1561C74.8339 45.6464 72.0097 46.023 70.5 47.9972L55.4514 66.1288L48.5523 58.7345C47.0265 56.7727 44.1992 56.4193 42.2375 57.9451C40.2757 59.471 39.9223 62.2982 41.4481 64.26L51.9295 76.26C52.786 77.3613 54.1049 78.003 55.5 77.9973C56.8951 77.9915 58.2087 77.3391 59.0562 76.2308L77.6492 53.4642Z"
                                    fill="#397BFF"
                                />
                                <path
                                    opacity="0.1"
                                    fill-rule="evenodd"
                                    clip-rule="evenodd"
                                    d="M22.5 2C22.5 0.895431 21.6046 0 20.5 0H15.5C14.3954 0 13.5 0.895431 13.5 2L13.5 13.5H2C0.895431 13.5 0 14.3954 0 15.5V20.5C0 21.6046 0.895431 22.5 2 22.5H13.5L13.5 34C13.5 35.1046 14.3954 36 15.5 36H20.5C21.6046 36 22.5 35.1046 22.5 34V22.5H34C35.1046 22.5 36 21.6046 36 20.5V15.5C36 14.3954 35.1046 13.5 34 13.5H22.5V2Z"
                                    fill="#397BFF"
                                />
                                <path
                                    opacity="0.3"
                                    fill-rule="evenodd"
                                    clip-rule="evenodd"
                                    d="M113.25 68C113.25 66.8954 112.355 66 111.25 66H110.75C109.645 66 108.75 66.8954 108.75 68V72.75H104C102.895 72.75 102 73.6454 102 74.75V75.25C102 76.3546 102.895 77.25 104 77.25H108.75V82C108.75 83.1046 109.645 84 110.75 84H111.25C112.355 84 113.25 83.1046 113.25 82V77.25H118C119.105 77.25 120 76.3546 120 75.25V74.75C120 73.6454 119.105 72.75 118 72.75H113.25V68Z"
                                    fill="#397BFF"
                                />
                                <path
                                    opacity="0.4"
                                    fill-rule="evenodd"
                                    clip-rule="evenodd"
                                    d="M76.7734 104C76.7734 102.895 75.878 102 74.7734 102H74.2734C73.1689 102 72.2734 102.895 72.2734 104V108.75H67.5234C66.4189 108.75 65.5234 109.645 65.5234 110.75V111.25C65.5234 112.355 66.4189 113.25 67.5234 113.25H72.2734V118C72.2734 119.105 73.1689 120 74.2734 120H74.7734C75.878 120 76.7734 119.105 76.7734 118V113.25H81.5234C82.628 113.25 83.5234 112.355 83.5234 111.25V110.75C83.5234 109.645 82.628 108.75 81.5234 108.75H76.7734V104Z"
                                    fill="#397BFF"
                                />
                            </g>
                            <defs>
                                <clipPath id="clip0_445_33713">
                                    <rect width="120" height="120" fill="white" />
                                </clipPath>
                            </defs>
                        </svg> : <Spin size="large" />}
                    <h2>{
                        stopKetStrt ? '正在停止' : isUserStopStatus ? '已手动停止' : isAllEndStatus ? `已完成${addstipdata.allInstallNum}张优惠券创建` : '正在创建优惠券，请勿关闭或刷新浏览器，窗口'
                    }</h2>
                    {(!isUserStopStatus && !isAllEndStatus) && <p>正在创建: {addstipdata.resetData && addstipdata.resetData.coupon_name}</p>}
                    <Space direction="vertical" align="center" size={4}>
                        <p><Tag type="success">成功</Tag> {addstipdata.success} 个优惠券</p>
                        {!!(addstipdata.fail * 1) && <p><Tag type="error">失败</Tag> {addstipdata.fail} 个优惠券</p>}
                    </Space>
                    <div style={{
                        width: 400
                    }}>
                        <span>{addstipdata.addUnser}/{addstipdata.allInstallNum}</span>
                        <Progress percent={addstipdata.stip} status="active" />
                    </div>
                    <Space>
                        {isUserStopStatus ? <Button onClick={() => {
                            // 重置创建相关数据
                            backOpenter()
                        }}>返回</Button> : isAllEndStatus ? null : <Button size="mini" onClick={() => {
                            stopAddConter()
                            setStopKetStrt(true)
                        }} loading={stopKetStrt}>停止创建</Button>}

                        {isAllEndStatus && <>
                            <Button type="primary" size="mini" onClick={() => {
                                // open('https://fxg.jinritemai.com/ffa/marketing/coupon/home?tab=manage')
                                backOpenter()
                                props && props.setcurrent && props.setcurrent('setCoupon')
                            }}>查看优惠券</Button>
                            <Button type="primary" size="mini" onClick={() => {
                                backOpenter()
                            }}>返回继续创建</Button>
                            <Button type="primary" size="mini" onClick={() => {
                                props && props.clearBox && props.clearBox()
                                setTimeout(_ => {
                                    backOpenter()
                                }, 200)

                            }}>关闭</Button>
                        </>
                        }
                    </Space>
                </Space>
            </div >}
        {(() => {
            let forList = goodsScope === 2 ? couponListDataAll : couponListDataShop
            const setFunData = goodsScope === 2 ? setCouponListDataAll : setCouponListDataShop
            return <Modal
                visible={addCouponList}
                title={editCouponStatus.status ? '编辑优惠券' : '添加优惠券'} // : 已添加' + forList.length + '张'
                okText=" 确定"
                cancelText=" 取消"
                destroyOnClose
                onCancel={() => {
                    setEditCounponStatus({
                        status: false,
                        index: -1
                    })
                    setAddCouponList(false)
                }}
                footer={
                    <div className="bote" style={{
                        display: 'flex',
                        justifyContent: 'space-between'
                    }}>
                        <div className="leter">
                            {!editCouponStatus.status &&
                                <Popover
                                    content={(
                                        <Space direction="vertical" >
                                            <div>这里可以添加多张优惠券</div>
                                            <div className="moter" style={{
                                                width: '100%',
                                                display: 'flex',
                                                justifyContent: 'flex-end'
                                            }}>
                                                <Button size="mini" type="primary" onClick={() => {
                                                    setShowAddCouponStuats(false)
                                                }}>知道了</Button>
                                            </div>
                                        </Space>
                                    )}
                                    visible={showAddCouponStuats}>

                                    {/* <Button size="mini" onClick={() => {
                                        forList.push(couponListDataFater(goodsScope))
                                        setFunData([...forList])
                                    }} icon={
                                        <Icon type="AddIcon"></Icon>}>
                                        新增优惠券
                                    </Button> */}

                                </Popover>
                            }
                        </div>
                        <div className="rngdtrr">
                            <Space>
                                <Button type="primary" size="mini" onClick={async () => {
                                    // 检查添加项
                                    let addkey = false
                                    // 这里请求活动是否配置情况


                                    forList.forEach(item => {
                                        item.reseteStatus = {
                                            errLijStatus: '',
                                            errLijTitle: null,
                                            errmonStatus: '',
                                            errmonTitle: null,
                                            errzekouStatus: '',
                                            errzekouTitle: null,
                                            fanStatus: '',
                                            fanTitle: null
                                        }
                                    })
                                    forList.forEach(async (item: any, index) => {
                                        switch (item.discountType) {
                                            case 1:
                                                if (!item.credit) {
                                                    item.reseteStatus.errLijStatus = 'error'
                                                    item.reseteStatus.errLijTitle = '立减金额不能为空'
                                                    addkey = true
                                                    // throw new Error('立减金额不能为空')
                                                }
                                                break;
                                            case 2:
                                                if (!item.threshold || !item.credit) {
                                                    item.reseteStatus.errmonStatus = 'error'
                                                    item.reseteStatus.errmonTitle = '满减金额不能为空'
                                                    addkey = true
                                                    return
                                                    // throw new Error('立减金额不能为空')
                                                }
                                                if (item.credit >= item.threshold) {
                                                    item.reseteStatus.errmonStatus = 'error'
                                                    item.reseteStatus.errmonTitle = '满额必须大于减额'
                                                    addkey = true
                                                    return
                                                }
                                                if ((item.credit / item.threshold) < 0.02) {
                                                    const mincater = Math.floor(item.threshold * 0.02)
                                                    const maxcater = Math.floor(item.threshold * 0.8)
                                                    item.reseteStatus.errmonStatus = 'error'
                                                    item.reseteStatus.errmonTitle = `优惠力度过小，需大于2%减额可填写的区间为¥${mincater}-¥${maxcater}`
                                                    addkey = true
                                                    return
                                                }
                                                if ((item.credit / item.threshold) > 0.8) {
                                                    const mincater = Math.floor(item.threshold * 0.02)
                                                    const maxcater = Math.floor(item.threshold * 0.8)
                                                    item.reseteStatus.errmonStatus = 'error'
                                                    item.reseteStatus.errmonTitle = `优惠力度过大，需小于80%减额可填写的区间为¥${mincater}-¥${maxcater}`
                                                    addkey = true
                                                    return
                                                }

                                                break;
                                            case 3:
                                                if (!item.discount) {
                                                    item.reseteStatus.errzekouStatus = 'error'
                                                    item.reseteStatus.errzekouTitle = '折扣不能不为空'
                                                    addkey = true
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                        if (!item.total_amount) {
                                            item.reseteStatus.fanStatus = 'error'
                                            item.reseteStatus.fanTitle = '发放数量不能为空'
                                            addkey = true

                                        }
                                    })
                                    if (addkey) {
                                        setFunData([...forList])
                                        message.error('请检查必填项')
                                        return
                                    }
                                    const getItemListeItemOne: any = forList[0]
                                    let getTimetype
                                    if (getItemListeItemOne.discountType == 1) {
                                        getTimetype = {
                                            "activity_tool_discount_type": 1,
                                            "credit": Number((getItemListeItemOne.credit * 100).toFixed(0)),
                                            "participate_type": 1,
                                            "activity_tool_type": 7,
                                            "validate_type": 2,
                                            "support_type": 1,
                                            "start_time": start_apply_time,
                                            "end_time": end_apply_time
                                        }
                                    }

                                    if (getItemListeItemOne.discountType == 2) {
                                        getTimetype = {
                                            "activity_tool_discount_type": 3,
                                            "threshold": Number((getItemListeItemOne.threshold * 100).toFixed(0)),
                                            "credit": Number((getItemListeItemOne.credit * 100).toFixed(0)),
                                            "participate_type": 1,
                                            "activity_tool_type": 7,
                                            "validate_type": 2,
                                            "support_type": 1,
                                            "start_time": start_apply_time,
                                            "end_time": end_apply_time
                                        }
                                    }
                                    if (getItemListeItemOne.discountType == 3) {
                                        getTimetype = {
                                            "activity_tool_discount_type": 4,
                                            "discount": Number((getItemListeItemOne.discount * 10).toFixed(0)),
                                            "participate_type": 1,
                                            "activity_tool_type": 7,
                                            "validate_type": 2,
                                            "support_type": 1,
                                            "start_time": start_apply_time,
                                            "end_time": end_apply_time
                                        }
                                    }
                                    const getAtserNow: any = await checkPromotionProductList(getTimetype)
                                    if (!getAtserNow.code) {
                                        if (!getAtserNow.data.activity_check_info.check_pass) {
                                            addkey = true
                                            if (getItemListeItemOne.discountType == 1) {
                                                getItemListeItemOne.reseteStatus.errLijStatus = 'error'
                                                getItemListeItemOne.reseteStatus.errLijTitle = getAtserNow.data.activity_check_info.reject_reason
                                            }
                                            if (getItemListeItemOne.discountType == 2) {
                                                getItemListeItemOne.reseteStatus.errmonStatus = 'error'
                                                getItemListeItemOne.reseteStatus.errmonTitle = getAtserNow.data.activity_check_info.reject_reason
                                            }
                                            if (getItemListeItemOne.discountType == 3) {
                                                getItemListeItemOne.reseteStatus.errzekouStatus = 'error'
                                                getItemListeItemOne.reseteStatus.errzekouTitle = getAtserNow.data.activity_check_info.reject_reason
                                            }
                                            setFunData([...forList])
                                            message.error('请检查填写是否符合最新优惠券规则！！！')
                                            return
                                        }
                                    }
                                    console.log('getAtserNow检查结果', getAtserNow)

                                    let setTibleData = goodsScope === 2 ? JSON.parse(JSON.stringify(couponListDataAll)) : JSON.parse(JSON.stringify(couponListDataShop))
                                    const setTableFun: any = goodsScope === 2 ? setCouponTableDataAll : setCouponTableDataShop
                                    setTibleData = setTibleData.map((element, index) => {
                                        // element.index = index
                                        const setTabData = {
                                            index,
                                            couponName: `${goodsScope === 2 ? '全店' : '商品'} - ${element.discountType === 1 ? '立减' : element.discountType === 2 ? '满减' : '折扣'}`,
                                            meter: (() => {
                                                let meterText = ''
                                                switch (element.discountType) {
                                                    case 1:
                                                        meterText = `立减 ${element.credit}`
                                                        break;
                                                    case 2:
                                                        meterText = `满 ${element.threshold} 减 ${element.credit}`
                                                        break;
                                                    case 3:
                                                        meterText = `打 ${element.discount} 折`
                                                        break;
                                                    default:
                                                        break;
                                                }
                                                return meterText
                                            })()
                                        }
                                        const addData = Object.assign(element, setTabData)
                                        return addData
                                    });
                                    setTableFun([...setTibleData])
                                    setAddCouponList(false)
                                    setEditCounponStatus({
                                        status: false,
                                        index: -1
                                    })
                                }}>添加</Button>
                                <Button size="mini" onClick={() => {
                                    setAddCouponList(false)
                                    setEditCounponStatus({
                                        status: false,
                                        index: -1
                                    })
                                }}>取消</Button>
                            </Space>
                        </div>
                    </div>
                }>
                {forList.map((item: any, index) => {
                    let { threshold, credit, discountType, reseteStatus } = item
                    if (editCouponStatus.status && editCouponStatus.index != index) {
                        return null
                    }
                    return (<div key={index}>
                        {/* <Tag bordered type="default">
                            优惠券：{index + 1}
                        </Tag> */}
                        {/* {!editCouponStatus.status && <Tag bordered type="default">
                                优惠券：{index + 1}
                            </Tag>} */}
                        <Space align="center" style={{
                            width: '100%'
                        }}>
                            <Form
                                labelCol={{ span: 4 }}
                                wrapperCol={{ span: 19 }}
                                layout="horizontal"
                                name="couponList"
                                initialValues={item}
                                key={index}
                                style={{
                                    width: '510px'
                                }}
                            >
                                <Form.Item
                                    name="discountType"
                                    label={goodsScope === 2 ? "全店通用" : "商品优惠券"}

                                >
                                    <Radio.Group onChange={(e: any) => {
                                        item.discountType = e.target.value
                                        setFunData([...forList])
                                    }}>
                                        <Radio value={1}>立减</Radio>
                                        <Radio value={2}>满减</Radio>
                                        <Radio value={3}>折扣</Radio>
                                    </Radio.Group>
                                </Form.Item>

                                {discountType === 1 &&
                                    <Form.Item
                                        name="credit"
                                        label="立减面额"
                                        help={reseteStatus.errLijTitle}
                                        validateStatus={reseteStatus.errLijStatus}
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入立减面额',
                                            },
                                        ]}>
                                        <InputNumber
                                            placeholder="请输入数字"
                                            min={1}
                                            max={1000}
                                            prefix="￥"
                                            onChange={(e: any) => {
                                                item.credit = e
                                                if (!item.credit) {
                                                    item.reseteStatus.errLijStatus = 'error'
                                                    item.reseteStatus.errLijTitle = '立减金额不能为空'
                                                } else {
                                                    item.reseteStatus.errLijStatus = ''
                                                    item.reseteStatus.errLijTitle = null
                                                }
                                                setFunData([...forList])
                                            }}
                                        />
                                    </Form.Item>
                                }

                                {discountType === 2 &&
                                    <Form.Item
                                        help={reseteStatus.errmonTitle}
                                        validateStatus={reseteStatus.errmonStatus}
                                        label="满减面额" >
                                        <Space>
                                            满
                                            <InputNumber
                                                placeholder="请输入数字"
                                                min={1}
                                                max={99999}
                                                prefix="￥"
                                                defaultValue={threshold}
                                                style={{
                                                    width: 32
                                                }}
                                                onChange={(e: any) => {
                                                    item.threshold = e
                                                    setFunData([...forList])
                                                }}
                                            />
                                            减
                                            <InputNumber
                                                placeholder="请输入数字"
                                                min={1}
                                                max={99999}
                                                prefix="￥"
                                                defaultValue={credit}
                                                style={{
                                                    width: 32
                                                }}
                                                onChange={(e: any) => {
                                                    item.credit = e
                                                    setFunData([...forList])
                                                }}
                                            />
                                            元
                                        </Space>
                                    </Form.Item>
                                }
                                {discountType === 3 &&
                                    <Form.Item
                                        name="discount"
                                        help={reseteStatus.errzekouTitle}
                                        validateStatus={reseteStatus.errzekouStatus}
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入折扣',
                                            },
                                        ]}
                                        label="折扣">
                                        <InputNumber
                                            placeholder="请输入折扣 2 - 9.9折"
                                            min={2}
                                            max={9.9}
                                            step={1}
                                            unit='折'
                                            onChange={(e: any) => {
                                                item.discount = e
                                                if (!item.discount) {
                                                    item.reseteStatus.errzekouStatus = 'error'
                                                    item.reseteStatus.errzekouTitle = '折扣不能不为空'
                                                } else {
                                                    item.reseteStatus.errzekouStatus = ''
                                                    item.reseteStatus.errzekouTitle = null
                                                }
                                                setFunData([...forList])
                                            }}
                                        />
                                    </Form.Item>}
                                <Form.Item
                                    name="total_amount"
                                    label="发放量"
                                    help={reseteStatus.fanTitle}
                                    validateStatus={reseteStatus.fanStatus}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入发放量',
                                        },
                                    ]}>
                                    <InputNumber
                                        placeholder="请输入数字"
                                        min={1}
                                        max={1000000}
                                        unit='张'
                                        onChange={(e: any) => {
                                            item.total_amount = e
                                            if (!item.total_amount) {
                                                item.reseteStatus.fanStatus = 'error'
                                                item.reseteStatus.fanTitle = '发放数量不能为空'
                                            } else {
                                                item.reseteStatus.fanStatus = ''
                                                item.reseteStatus.fanTitle = null
                                            }

                                            setFunData([...forList])
                                        }}
                                    />
                                </Form.Item>
                                <Form.Item name="max_apply_times" label="每人领">
                                    <Radio.Group onChange={(e: any) => {
                                        item.max_apply_times = e.target.value
                                        setFunData([...forList])
                                    }}>
                                        <Radio value={1}>1张</Radio>
                                        <Radio value={2}>2张</Radio>
                                        <Radio value={3}>3张</Radio>
                                        <Radio value={4}>4张</Radio>
                                        <Radio value={5}>5张</Radio>
                                    </Radio.Group>
                                </Form.Item>

                            </Form>
                            {false && !editCouponStatus.status && <Icon
                                type="DeleteIcon" style={{
                                    fontSize: 16,
                                    color: 'red',
                                    cursor: 'pointer'
                                }}
                                onClick={() => {

                                    if (forList.length <= 1) {
                                        message.warning('至少保留一个优惠券')
                                        return
                                    }
                                    forList.splice(index, 1)
                                    setFunData([...forList])
                                }}
                            ></Icon>}

                        </Space>
                        {(index !== (forList.length - 1) && !editCouponStatus.status) && <Divider />}
                    </div>)
                })}
            </Modal>
        })()}
    </div>)
}
export default forwardRef(Coupon)